package com.jwd.avmanager.server;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;

/**
 * 用于redis管理
 */
public class JedisClient {


    private static JedisClient instance;

    private static JedisPool jedisPool;

    private JedisClient() {

    }

    public static JedisClient getInstance() {
        if (jedisPool == null) {
            throw new RuntimeException("jedisPool is null");
        }
        if (instance == null) {
            synchronized (JedisClient.class) {
                if (instance == null) {
                    instance = new JedisClient();
                }
            }

        }
        return instance;
    }


    public static void initJedis() {

        //创建连接池的配置对象，进行一些属性的配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(20);
        jedisPoolConfig.setMaxIdle(12);
        jedisPoolConfig.setMaxWait(Duration.ofMillis(200));
        String host = "localhost";
        int port = 6379;
        //使用jedis连接池
        try {
            jedisPool = new JedisPool(jedisPoolConfig, host, port);
            Jedis resource = jedisPool.getResource();
            resource.close();
        } catch (Exception e) {
            //TODO 打印错误日志，redis不能连接的话，不能启动服务
            System.out.println("redis连接失败，服务退出");
            System.exit(1);
        }
    }

    /**
     * 通过字符串key获取value
     * @param key
     * @return
     */
    public String get(String key) {
        Jedis resource = jedisPool.getResource();
        String s = resource.get(key);
        resource.close();
        return s;
    }
}
